/*
 * Copyright 2007 Xplayat, S.L. All rights reserved.
 * Propiedad de Xplayat. 
 */
package es.xpt.ysf.web.service;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import es.xpt.ysf.logging.Log;
import es.xpt.ysf.logging.LogManager;

public class TimeLog implements Filter{

  private long time;
  private Log log;
//  private OperatingSystemMXBean operatingSystemMXBean = null;
//  private Method m = null;

  public TimeLog() {  }
  
  public void init(FilterConfig filterConfig) {
    time = Long.valueOf(filterConfig.getInitParameter("milis"));
    log = LogManager.getLog(getClass());
//    if (Boolean.valueOf(filterConfig.getInitParameter("filesOpen")) ) {
//	    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
//	    try {
//			m = operatingSystemMXBean.getClass().getDeclaredMethod("getOpenFileDescriptorCount");
//			m.setAccessible(true);
//		} catch (SecurityException e) {
//			m  = null;
//		} catch (NoSuchMethodException e) {
//			m = null;
//		}	
//	}
  }
  
//  public int invoke () {
//	  if ( m!=null ) {
//		  try {
//			Object o = m.invoke(operatingSystemMXBean);
//			return Integer.valueOf(o.toString());
//		} catch (IllegalArgumentException e) {
//			m = null;
//		} catch (IllegalAccessException e) {
//			m = null;
//		} catch (InvocationTargetException e) {
//			m = null;
//		}
//	  }
//	  return 0;
//  }

  public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, FilterChain chain)
      throws java.io.IOException, ServletException {
   
	  servletRequest.setCharacterEncoding("UTF-8");
	  servletResponse.setCharacterEncoding("UTF-8");
	  
	  if ( log.isDebugEnabled() ) {
	  
	log.debug("NEW REQUEST FOR " + ((HttpServletRequest)servletRequest).getRequestURI());
    long t0 = System.currentTimeMillis();
//    int f0 = invoke();
    chain.doFilter(servletRequest, servletResponse);
    long t1 = System.currentTimeMillis();
//    int f1 = invoke();
    long diff = t1-t0;
    if ( diff>time ) {
    	log.debug("SLOW RESPONSE IN: " + ((HttpServletRequest)servletRequest).getRequestURI() + "---->" + diff + " milis");
    }
//    if ( f1-f0 > 0 ) {
//    	log.info("FILES OPEN IN: " + ((HttpServletRequest)servletRequest).getRequestURI() + "---->" + (f1-f0) + " new files open");
//    }
	  } else {
		  chain.doFilter(servletRequest, servletResponse);
	  }
 
  }
	@Override
	public void destroy() {
		
	}
}